package database

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"tools-api/src/common/def"
	"xorm.io/xorm"
)

var (
	ToolsEngine *xorm.Engine
	JCJEngine   *xorm.Engine
)

// Connect 链接数据库
func Connect() {
	config := def.Config.GetStringMap("db")
	url := fmt.Sprintf("%s:%s@tcp(%s:%d)/%%%s?charset=%s",
		config["user"].(string),
		config["password"].(string),
		config["host"].(string),
		config["port"].(int),
		"s", // 保留占位符
		config["charset"].(string),
	)
	ToolsEngine = connectDB(url, "tools")
	JCJEngine = connectDB(url, "jucaiji")
}

func connectDB(url, name string) *xorm.Engine {
	engine, err := xorm.NewEngine("mysql", fmt.Sprintf(url, name))
	if err != nil {
		panic(err)
	}
	err = engine.Ping()
	if err != nil {
		fmt.Println(fmt.Sprintf("连接数据库失败: %v", err))
		panic(err)
	}
	return engine
}
